# -*- coding:utf-8 -*-
# @Time: 2020/8/25 10:37
# @Author: liupengfei
# @File: serializers.py
import json
import random, re, string

from django_redis import get_redis_connection
from rest_framework import serializers
from django.contrib.auth import get_user_model
from rest_framework_jwt.settings import api_settings
from rest_framework.exceptions import ValidationError
from utils.send_sms import SMS
from .models import Member, MemberHouse, MemberRecord

User = get_user_model()
jwt_payload_hander = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER


class MemberSignSerializer(serializers.Serializer):
    def validate(self, attrs):
        userinfo = json.loads(self.initial_data.get('userInfo'))
        mobile = self.initial_data.get('mobile')
        password = self.initial_data.get('password')
        # 小程序的用户信息
        if not mobile or not password:
            raise ValidationError('请输入用户名或者密码')

        # 验证通过
        user = User.objects.filter(username=mobile).first()
        print(user)
        if not user:
            """注册"""
            user = User.objects.create_user(username=mobile, nickname=userinfo['nickName'], password=password)
            # {'nickName': 'QiaoFinn_lpf', 'gender': 1, 'language': 'zh_CN', 'city': '烟台', 'province': '山东', 'country': '中国', 'avatarUrl': 'https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJkKNKezgVwHibQboGP19bTuyPKM4ukmx3jJU0FjNs1GLblx4VXpt9ic
            # kgyhMia8E3vnV5PvlFkKxxJg/132'}
            Member.objects.create(user=user, face_url=userinfo['avatarUrl'], gender=userinfo['gender'],
                                  province=userinfo['province'], city=userinfo['city'])
        else:
            if not user.check_password(password):
                raise ValidationError('密码错误')
        payload = jwt_payload_hander(user)

        return {
            'token': jwt_encode_handler(payload),
            'username': user.nickname,
            'identity': user.member.identity
        }


class MemberMobileSignSerializer(serializers.Serializer):

    def validate(self, attrs):
        userinfo = json.loads(self.initial_data.get('userInfo'))
        mobile = self.initial_data.get('mobile')
        vcode = self.initial_data.get('vcode')
        # 小程序的用户信息
        if not mobile or not vcode:
            raise ValidationError('参数无效')

        # 验证码验证,从redis中取出来
        conn = get_redis_connection()
        redis_code = conn.get(mobile)

        if not redis_code:
            raise ValidationError('短信验证码已失效')
        if vcode != redis_code.decode('utf-8'):
            raise ValidationError('短信验证码错误')

        # 验证通过
        user = User.objects.filter(username=mobile).first()
        if not user:
            """注册"""
            user = User.objects.create_user(username=mobile, nickname=userinfo['nickName'])
            # {'nickName': 'QiaoFinn_lpf', 'gender': 1, 'language': 'zh_CN', 'city': '烟台', 'province': '山东', 'country': '中国', 'avatarUrl': 'https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJkKNKezgVwHibQboGP19bTuyPKM4ukmx3jJU0FjNs1GLblx4VXpt9ic
            # kgyhMia8E3vnV5PvlFkKxxJg/132'}
            Member.objects.create(user=user, face_url=userinfo['avatarUrl'], gender=userinfo['gender'],
                                  province=userinfo['province'], city=userinfo['city'])
            # MemberRecord.objects.create(content_object=user, user=user, operate=MemberRecord.SIGN, describe='第一次注册')

        payload = jwt_payload_hander(user)

        return {
            'token': jwt_encode_handler(payload),
            'username': user.nickname
        }


class SendSmsSerializer(serializers.Serializer):
    mobile = serializers.CharField(max_length=11, min_length=11,
                                   error_messages={'min_length': '请输入正确的手机号!', 'max_length': '请输入正确的手机号'})

    def validate_mobile(self, mobile):
        regex_mobile = "^1[358]\d{9}$|^147\d{8}$|^176\d{8}$"
        if not re.match(regex_mobile, mobile):
            raise serializers.ValidationError("请输入正确的手机号!")

        # 生成短信
        code = ''.join(random.sample(string.digits, 6))
        # 发送短信
        sms = SMS()
        resp = sms.send('+86%s' % mobile, code)
        '''
        {'SerialNo': '2019:-8153317968300304047', 'PhoneNumber': '+8617616153358', 'Fee': 1, 'SessionContext': '', 
        'Code': 'Ok', 'Message': 'send success', 'IsoCode': 'CN'}
        '''
        if resp['Code'] != 'Ok':
            raise serializers.ValidationError('短信发送失败,{}'.format(resp['Message']))
        # 保存到redis
        redis_conn = get_redis_connection()
        redis_conn.set(mobile, code, ex=60)
        return mobile


class MemberJwtSerializer(serializers.ModelSerializer):
    '''刷新token返回的数据'''

    class Meta:
        model = Member
        fields = '__all__'


class MemeberInfoAppSerializer(serializers.ModelSerializer):
    username = serializers.CharField(source='user.username')
    nickname = serializers.CharField(source='user.nickname')

    # 小程序用户信息
    class Meta:
        model = Member
        fields = ('username', 'nickname', 'face_url', 'gender')


class MemberHouseSerializer(serializers.ModelSerializer):
    door_model_arr = serializers.SerializerMethodField(read_only=True)

    def get_door_model_arr(self, obj):
        return list(map(int, obj.door_model.split(',')))

    # 我的房子
    class Meta:
        model = MemberHouse
        fields = '__all__'

    def create(self, validated_data):
        self_request = self.context['request']
        MemberHouse.objects.filter(member=self_request.user.member).delete()
        validated_data['member'] = self_request.user.member
        instance = super(MemberHouseSerializer, self).create(validated_data)
        return instance


class MemberRecordSerializer(serializers.ModelSerializer):
    create_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M', read_only=True)
    content = serializers.SerializerMethodField()
    color = serializers.SerializerMethodField()
    icon = serializers.SerializerMethodField()

    def get_icon(self, obj):
        icons = ['radioboxfill', 'evaluate_fill', 'favorfill', 'camerafill', 'likefill', 'notificationfill', 'samefill',
                 'discoverfill', 'selectionfill', 'lightfill', 'countdownfill', 'choicenessfill', 'colorlens',
                 'tagfill', 'hotfill', 'activityfill']

        return icons[random.randint(0, len(icons) - 1)]

    def get_color(self, obj):
        colors = ['red', 'orange', 'yellow', 'green', 'cyan', 'blue', 'purple', 'mauve', 'pink', 'brown', 'grey',
                  'gray']
        return colors[random.randint(0, len(colors) - 1)]

    def get_content(self, obj):
        if obj.content_type == MemberRecord.get_content_type('Article'):
            return {
                'content_type': 'Article'.lower(),
                'title': obj.content_object.title,
                'thumbnail': obj.content_object.thumbnail.get_url(),
            }
        if obj.content_type == MemberRecord.get_content_type('House'):
            return {
                'content_type': 'House'.lower(),
                "describe": obj.content_object.describe,
                "thumbnail": obj.content_object.thumbnail.get_url(),
                "style": obj.content_object.style.name,
            }
        return ''

    # 用户记录
    class Meta:
        model = MemberRecord
        fields = ('object_id', 'create_time', 'content', 'color', 'icon')
